import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'page_flip_config.dart';
import 'page_flip_controller.dart';
import 'page_flip_types.dart';
import 'page_container.dart';

/// 主要的翻页Widget
class PageFlipWidget extends StatefulWidget {
  final PageFlipController controller;
  final PageFlipConfig? config;
  final Widget? menuBuilder;
  final VoidCallback? onMenuToggle;

  const PageFlipWidget({
    super.key,
    required this.controller,
    this.config,
    this.menuBuilder,
    this.onMenuToggle,
  });

  @override
  State<PageFlipWidget> createState() => _PageFlipWidgetState();
}

class _PageFlipWidgetState extends State<PageFlipWidget>
    with TickerProviderStateMixin {
  bool _showMenu = false;
  late PageFlipConfig _effectiveConfig;

  // 3个页面容器用于复用
  late List<PageContainer> _pageContainers;

  @override
  void initState() {
    super.initState();
    _effectiveConfig = widget.config ?? const PageFlipConfig();
    _initPageContainers();
    _setupController();
  }

  @override
  void didUpdateWidget(PageFlipWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.controller != widget.controller) {
      _initPageContainers();
      _setupController();
    }
    _effectiveConfig = widget.config ?? widget.controller.config;
  }

  /// 初始化3个页面容器
  void _initPageContainers() {
    _pageContainers = List.generate(
      PageContainerManager.containerCount,
      (index) => PageContainer(
        key: ValueKey('page_container_$index'),
        containerId: index,
        pageBuilder: widget.controller.pageBuilder,
        currentPageIndex:
            widget.controller.containerManager.getContainerPageIndex(index),
        onPageBuilt: () {
          // 页面构建完成后的回调
          if (mounted) {
            setState(() {});
          }
        },
      ),
    );
  }

  void _setupController() {
    // 初始化动画控制器
    widget.controller.initAnimationControllers(this);

    // 监听控制器变化
    widget.controller.addListener(_onControllerChanged);

    // 设置系统UI模式
    _updateSystemUIMode();
  }

  void _onControllerChanged() {
    if (mounted) {
      setState(() {});
    }
  }

  void _updateSystemUIMode() {
    if (!_effectiveConfig.showStatus) {
      SystemChrome.setEnabledSystemUIMode(
        SystemUiMode.manual,
        overlays: [],
      );
    } else {
      SystemChrome.setEnabledSystemUIMode(
        SystemUiMode.manual,
        overlays: SystemUiOverlay.values,
      );
    }
  }

  void _toggleMenu() {
    setState(() {
      _showMenu = !_showMenu;
    });
    widget.onMenuToggle?.call();
  }

  @override
  void dispose() {
    widget.controller.removeListener(_onControllerChanged);
    // 恢复系统UI模式
    SystemChrome.setEnabledSystemUIMode(
      SystemUiMode.manual,
      overlays: SystemUiOverlay.values,
    );
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: _effectiveConfig.backgroundColor,
      child: LayoutBuilder(
        builder: (context, constraints) {
          final size = Size(constraints.maxWidth, constraints.maxHeight);

          return Focus(
            autofocus: _effectiveConfig.enableKeyboard,
            onKeyEvent: (node, event) {
              if (_effectiveConfig.enableKeyboard && !_showMenu) {
                widget.controller.handleKeyPress(event);
                return KeyEventResult.handled;
              }
              return KeyEventResult.ignored;
            },
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onHorizontalDragStart: _effectiveConfig.enableGestures &&
                      !_showMenu
                  ? (details) {
                      debugPrint('开始水平拖拽: ${details.globalPosition}');
                      widget.controller.handleDragStart(details); // 🆕 调用手势开始处理
                    }
                  : null,
              onHorizontalDragUpdate:
                  _effectiveConfig.enableGestures && !_showMenu
                      ? (details) {
                          if (_effectiveConfig.enableTapToFlip) {
                            debugPrint('水平拖拽更新: ${details.delta}');
                          }
                          widget.controller.handleDragUpdate(details, size);
                        }
                      : null,
              onHorizontalDragEnd: _effectiveConfig.enableGestures && !_showMenu
                  ? (details) {
                      if (_effectiveConfig.enableTapToFlip) {
                        debugPrint(
                            '水平拖拽结束: ${details.velocity.pixelsPerSecond}');
                      }
                      widget.controller.handleDragEnd(details);
                    }
                  : null,
              onTapUp: _effectiveConfig.enableGestures && !_showMenu
                  ? (details) {
                      if (_effectiveConfig.enableTapToFlip) {
                        debugPrint('点击: ${details.globalPosition}');
                      }
                      // 检查是否应该切换菜单
                      final shouldToggleMenu = _shouldToggleMenu(details, size);
                      if (shouldToggleMenu) {
                        _toggleMenu();
                      } else {
                        widget.controller.handleTap(details, size);
                      }
                    }
                  : null,
              child: Stack(
                children: [
                  // 背景
                  Container(
                    width: double.infinity,
                    height: double.infinity,
                    color: _effectiveConfig.backgroundColor,
                  ),

                  // 页面层 - 直接渲染Widget
                  ..._buildPageLayers(size),

                  // 菜单层
                  if (_showMenu && widget.menuBuilder != null)
                    Positioned.fill(
                      child: GestureDetector(
                        onTap: () => setState(() => _showMenu = false),
                        child: Container(
                          color: Colors.black54,
                          child: Center(
                            child: widget.menuBuilder!,
                          ),
                        ),
                      ),
                    ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  /// 构建页面层 - 使用3个页面容器复用
  List<Widget> _buildPageLayers(Size size) {
    // 更新页面容器的数据
    _updatePageContainers();

    // 根据交互模式选择渲染方式
    switch (_effectiveConfig.interactionMode) {
      case PageFlipInteractionMode.interactive:
        return _buildInteractivePageLayers(size);
      case PageFlipInteractionMode.picture:
        return _buildPicturePageLayers(size);
      case PageFlipInteractionMode.auto:
        return _buildAutoPageLayers(size);
    }
  }

  /// 更新页面容器的数据
  void _updatePageContainers() {
    debugPrint('🔧 开始更新页面容器...');
    for (int i = 0; i < _pageContainers.length; i++) {
      final newPageIndex =
          widget.controller.containerManager.getContainerPageIndex(i);
      final currentContainer = _pageContainers[i];

      debugPrint(
          '🔧 容器$i: 当前页面${currentContainer.currentPageIndex} -> 新页面$newPageIndex');

      // 如果页面索引发生变化，需要重新创建容器
      if (currentContainer.currentPageIndex != newPageIndex) {
        debugPrint(
            '🔧 重新创建容器$i，页面索引: ${currentContainer.currentPageIndex} -> $newPageIndex');
        _pageContainers[i] = PageContainer(
          key: ValueKey('page_container_${i}_$newPageIndex'),
          containerId: i,
          pageBuilder: widget.controller.pageBuilder,
          currentPageIndex: newPageIndex,
          onPageBuilt: () {
            debugPrint('🔧 容器$i页面构建完成，显示页面$newPageIndex');
            if (mounted) {
              setState(() {});
            }
          },
        );
      }
    }
    debugPrint('🔧 页面容器更新完成');
  }

  /// 交互模式：使用页面容器复用
  List<Widget> _buildInteractivePageLayers(Size size) {
    // 警告：交互模式下只有覆盖效果能保证完全交互性
    if (_effectiveConfig.animation != PageFlipAnimation.cover) {
      debugPrint('⚠️ 警告：交互模式下建议使用覆盖效果，其他动画可能影响Widget交互性');
    }

    final layers = <Widget>[];
    final currentIndex = widget.controller.currentIndex;

    // 调试信息：打印当前状态
    debugPrint('🔍 当前索引: $currentIndex');
    final containerMapping =
        widget.controller.containerManager.getAllContainerPageIndexes();
    debugPrint('🔍 容器映射: $containerMapping');

    // 调试信息：打印每个容器的实际内容
    for (int i = 0; i < _pageContainers.length; i++) {
      final container = _pageContainers[i];
      debugPrint('🔍 容器$i实际显示: 页面${container.currentPageIndex}');
    }

    // 第1层（底层）：下一页容器 (容器2)
    final nextIndex = currentIndex + 1;
    if (nextIndex < widget.controller.pageCount) {
      final nextContainerId =
          widget.controller.containerManager.getContainerIdForPage(nextIndex);
      if (nextContainerId != null && nextContainerId < _pageContainers.length) {
        final actualContainer = _pageContainers[nextContainerId];
        debugPrint(
            '🔍 底层显示: 容器$nextContainerId -> 期望页面$nextIndex, 实际页面${actualContainer.currentPageIndex}');
        layers.add(Positioned.fill(child: actualContainer));
      }
    }

    // 第2层（中层）：当前页容器 (容器1)
    if (currentIndex >= 0 && currentIndex < widget.controller.pageCount) {
      final nextController =
          widget.controller.getAnimationController(nextIndex);
      if (nextController != null && nextController.value < 0.99) {
        // 当前页向左滑出的动画
        final currentContainerId = widget.controller.containerManager
            .getContainerIdForPage(currentIndex);
        if (currentContainerId != null &&
            currentContainerId < _pageContainers.length) {
          final actualContainer = _pageContainers[currentContainerId];
          debugPrint(
              '🔍 中层动画显示: 容器$currentContainerId -> 期望页面$currentIndex, 实际页面${actualContainer.currentPageIndex}');
          layers.add(
            Positioned.fill(
              child: AnimatedBuilder(
                animation: nextController,
                builder: (context, child) {
                  final progress = 1.0 - nextController.value;
                  return _buildCurrentPageSlideOut(
                      actualContainer, progress, size);
                },
              ),
            ),
          );
        }
      } else {
        // 没有动画时显示静态当前页
        final currentContainerId = widget.controller.containerManager
            .getContainerIdForPage(currentIndex);
        if (currentContainerId != null &&
            currentContainerId < _pageContainers.length) {
          final actualContainer = _pageContainers[currentContainerId];
          debugPrint(
              '🔍 中层静态显示: 容器$currentContainerId -> 期望页面$currentIndex, 实际页面${actualContainer.currentPageIndex}');
          layers.add(Positioned.fill(child: actualContainer));
        }
      }
    }

    // 第3层（顶层）：上一页容器 (容器0)
    final prevIndex = currentIndex - 1;
    if (prevIndex >= 0) {
      final prevController =
          widget.controller.getAnimationController(prevIndex);
      if (prevController != null && prevController.value < 0.99) {
        final prevContainerId =
            widget.controller.containerManager.getContainerIdForPage(prevIndex);
        if (prevContainerId != null &&
            prevContainerId < _pageContainers.length) {
          layers.add(
            Positioned.fill(
              child: AnimatedBuilder(
                animation: prevController,
                builder: (context, child) {
                  final progress = 1.0 - prevController.value;
                  return _buildPrevPageSlideIn(
                      _pageContainers[prevContainerId], progress, size);
                },
              ),
            ),
          );
        }
      }
    }

    return layers;
  }

  /// 构建当前页滑出动画（根据动画类型）
  Widget _buildCurrentPageSlideOut(Widget page, double progress, Size size) {
    switch (_effectiveConfig.animation) {
      case PageFlipAnimation.cover:
        // 覆盖效果：简单向左滑出
        return Transform.translate(
          offset: Offset(-progress * size.width, 0),
          child: Container(
            decoration: BoxDecoration(
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.3 * progress),
                  blurRadius: 15,
                  offset: const Offset(5, 0),
                ),
              ],
            ),
            child: page,
          ),
        );

      case PageFlipAnimation.curl:
        // 卷曲效果：页面收缩并倾斜
        return Transform(
          alignment: Alignment.centerRight,
          transform: Matrix4.identity()
            ..setEntry(3, 2, 0.001) // perspective
            ..rotateY(-progress * 0.5) // 轻微的Y轴旋转
            ..scale(1.0 - progress * 0.3) // 缩放
            ..translate(-progress * size.width * 0.7, 0, 0), // 向左移动
          child: ClipRect(
            child: Container(
              decoration: BoxDecoration(
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.4 * progress),
                    blurRadius: 20,
                    offset: Offset(10 * progress, 0),
                  ),
                ],
              ),
              child: Opacity(
                opacity: 1.0 - progress * 0.3,
                child: page,
              ),
            ),
          ),
        );

      case PageFlipAnimation.flip:
        // 3D翻转效果
        return Transform(
          alignment: Alignment.centerLeft,
          transform: Matrix4.identity()
            ..setEntry(3, 2, 0.001)
            ..rotateY(-progress * 1.57), // 90度翻转
          child: Container(
            decoration: BoxDecoration(
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.5 * progress),
                  blurRadius: 25,
                  offset: const Offset(8, 0),
                ),
              ],
            ),
            child: page,
          ),
        );

      case PageFlipAnimation.simulation:
        // 仿真效果1：波浪形变形
        return Transform(
          alignment: Alignment.centerRight,
          transform: Matrix4.identity()
            ..setEntry(3, 2, 0.0008)
            ..rotateY(-progress * 0.8),
          child: ClipPath(
            clipper: _WaveClipper(progress),
            child: Container(
              decoration: BoxDecoration(
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.35 * progress),
                    blurRadius: 18,
                    offset: Offset(6 * progress, 0),
                  ),
                ],
              ),
              child: Transform.translate(
                offset: Offset(-progress * size.width * 0.5, 0),
                child: page,
              ),
            ),
          ),
        );

      case PageFlipAnimation.simulation2:
        // 仿真效果2：页面折叠
        return Transform(
          alignment: Alignment.centerRight,
          transform: Matrix4.identity()
            ..setEntry(3, 2, 0.0005)
            ..rotateY(-progress * 1.2)
            ..translate(-progress * size.width * 0.6, 0, -progress * 50),
          child: Container(
            decoration: BoxDecoration(
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.45 * progress),
                  blurRadius: 22,
                  offset: Offset(12 * progress, 0),
                ),
              ],
            ),
            child: ClipRect(
              child: Opacity(
                opacity: 1.0 - progress * 0.4,
                child: page,
              ),
            ),
          ),
        );

      default:
        return Transform.translate(
          offset: Offset(-progress * size.width, 0),
          child: page,
        );
    }
  }

  /// 构建上一页滑入动画（根据动画类型）
  Widget _buildPrevPageSlideIn(Widget page, double progress, Size size) {
    switch (_effectiveConfig.animation) {
      case PageFlipAnimation.cover:
        // 覆盖效果：从左侧滑入
        return Transform.translate(
          offset: Offset(-(1.0 - progress) * size.width, 0),
          child: Container(
            decoration: BoxDecoration(
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.2 * progress),
                  blurRadius: 10,
                  offset: const Offset(5, 0),
                ),
              ],
            ),
            child: page,
          ),
        );

      case PageFlipAnimation.curl:
      case PageFlipAnimation.flip:
      case PageFlipAnimation.simulation:
      case PageFlipAnimation.simulation2:
        // 复杂动画的上一页滑入效果
        return Transform.translate(
          offset: Offset(-(1.0 - progress) * size.width, 0),
          child: Container(
            decoration: BoxDecoration(
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.3 * progress),
                  blurRadius: 15,
                  offset: const Offset(8, 0),
                ),
              ],
            ),
            child: page,
          ),
        );

      default:
        return Transform.translate(
          offset: Offset(-(1.0 - progress) * size.width, 0),
          child: page,
        );
    }
  }

  /// 图片模式：使用Picture实现所有动画
  List<Widget> _buildPicturePageLayers(Size size) {
    final layers = <Widget>[];
    final currentIndex = widget.controller.currentIndex;

    // 第1层（底层）：下一页容器
    final nextIndex = currentIndex + 1;
    if (nextIndex < widget.controller.pageCount) {
      final nextContainerId =
          widget.controller.containerManager.getContainerIdForPage(nextIndex);
      if (nextContainerId != null && nextContainerId < _pageContainers.length) {
        layers.add(
          Positioned.fill(
            child: _pageContainers[nextContainerId],
          ),
        );
      }
    }

    // 第2层（中层）：当前页容器 - 使用CustomPainter实现复杂动画
    if (currentIndex >= 0 && currentIndex < widget.controller.pageCount) {
      final nextController =
          widget.controller.getAnimationController(nextIndex);
      if (nextController != null && nextController.value < 0.99) {
        // 当前页向左滑出的动画 - 使用CustomPainter
        final currentContainerId = widget.controller.containerManager
            .getContainerIdForPage(currentIndex);
        if (currentContainerId != null &&
            currentContainerId < _pageContainers.length) {
          layers.add(
            Positioned.fill(
              child: AnimatedBuilder(
                animation: nextController,
                builder: (context, child) {
                  final progress = 1.0 - nextController.value; // 动画进度 0.0-1.0
                  return Stack(
                    children: [
                      // 显示当前页面
                      _buildCurrentPageSlideOut(
                          _pageContainers[currentContainerId], progress, size),
                      // 添加Picture模式指示器
                      Positioned(
                        top: 20,
                        left: 20,
                        child: Container(
                          padding: const EdgeInsets.all(8),
                          decoration: BoxDecoration(
                            color: Colors.orange.withOpacity(0.8),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Text(
                            '🎨 Picture模式\n${_effectiveConfig.animation.name}',
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
          );
        }
      } else {
        // 没有动画时显示静态当前页
        final currentContainerId = widget.controller.containerManager
            .getContainerIdForPage(currentIndex);
        if (currentContainerId != null &&
            currentContainerId < _pageContainers.length) {
          layers.add(
            Positioned.fill(
              child: _pageContainers[currentContainerId],
            ),
          );
        }
      }
    }

    return layers;
  }

  /// 自动模式：根据动画类型智能选择
  List<Widget> _buildAutoPageLayers(Size size) {
    // 只有覆盖效果适合保持完全交互性
    // 其他复杂动画会影响Widget交互，需要Picture模式
    if (_effectiveConfig.animation == PageFlipAnimation.cover) {
      return _buildInteractivePageLayers(size);
    } else {
      return _buildPicturePageLayers(size);
    }
  }

  /// 检查是否应该切换菜单
  bool _shouldToggleMenu(TapUpDetails details, Size size) {
    final menuZoneSize = size * _effectiveConfig.menuZoneRatio;
    final menuZoneRect = Rect.fromCenter(
      center: Offset(size.width / 2, size.height / 2),
      width: menuZoneSize.width,
      height: menuZoneSize.height,
    );
    return menuZoneRect.contains(details.globalPosition);
  }
}

/// 波浪形裁剪器用于simulation动画效果
class _WaveClipper extends CustomClipper<Path> {
  final double progress;

  _WaveClipper(this.progress);

  @override
  Path getClip(Size size) {
    final path = Path();
    final waveHeight = 20.0 * progress;
    final waveLength = size.width / 4;

    path.moveTo(0, 0);
    path.lineTo(size.width * (1.0 - progress), 0);

    // 创建波浪形右边缘
    for (double i = 0; i <= size.height; i += waveLength) {
      final x = size.width * (1.0 - progress) +
          (i % (waveLength * 2) < waveLength ? waveHeight : -waveHeight);
      path.lineTo(x, i);
    }

    path.lineTo(size.width * (1.0 - progress), size.height);
    path.lineTo(0, size.height);
    path.close();

    return path;
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return oldClipper is! _WaveClipper || oldClipper.progress != progress;
  }
}
